<?php
/**
 * Created by PhpStorm.
 * User: Jessewang
 * Date: 2017/3/29
 * Time: 上午11:34
 */

namespace App\Libs;
use Swoole;
use Swoole\Client\Http;
class WeChatApi
{
    const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
    const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
    const OAUTH_USERINFO_URL = '/sns/userinfo?';
    const OAUTH_AUTH_URL = '/sns/auth?';

    public  $appid=null;
    public  $appkey = null;

    function  __construct()
    {
        $config = \Swoole::$php->config["sns"];

        $this->appid = $config['wechat']['appid'];
        $this->appkey = $config['wechat']['appkey'];
    }

    function getAccessToken($code)
    {
        $httpClient = new Http("api.weixin.qq.com");
        $data = array(
            "appid"=>$this->appid,
            'secret'=>$this->appkey,
            'code'=>$code,
            'grant_type'=>'authorization_code'

        );
        $ret = $httpClient->get("api.weixin.qq.com/sns/oauth2/access_token",$data);
        if($httpClient->getStatus() == 200)
        $ret = $httpClient->getContent();
        return $ret;
    }

    function  getUserInfo($accesstoken,$openid)
    {
        $httpClient = new Http();
        $data = array(
            "access_token"=>$accesstoken,
            'openid'=>$openid,

        );
        $ret = $httpClient->get("https://api.weixin.qq.com/sns/userinfo",$data);

        return $ret;
    }
    function auth($accesstoken,$openid)
    {
        $httpClient = new Http();
        $data = array(
            "access_token"=>$accesstoken,
            'openid'=>$openid,

        );
        $ret = $httpClient->get("https://api.weixin.qq.com//sns/auth",$data);

        if($ret)
        {
            $ret = json_decode($ret);
            if($ret['errcode'] ==0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}